class Solution(object):
    def validateBinaryTreeNodes(self, n, leftChild, rightChild):
        p = [i for i in range(n)]
        t = set()
        self.count = n

        def find(x):
            if x == p[x]:
                return x
            else:
                p[x] = find(p[x])
                return p[x]

        def union(x, y):
            rootx = find(x)
            rooty = find(y)
            if rootx == rooty:
                return False
            else:
                if rootx < rooty:
                    p[rooty] = rootx
                else:
                    p[rootx] = rooty
                self.count -= 1
                return True
        for i in range(n):
            if leftChild[i] != -1:
                if leftChild[i] in t:
                    return False
                t.add(leftChild[i])
                if not union(i, leftChild[i]):
                    return False
            if rightChild[i] != -1:
                if rightChild[i] in t:
                    return False
                t.add(rightChild[i])
                if not union(i, rightChild[i]):
                    return False
        return self.count == 1

data = Solution()
n = 4
left = [1,-1,3,-1]
right = [2,-1,-1,-1]
print(data.validateBinaryTreeNodes(n, left, right))